//
//  KLMNavigationController.swift
//  KLM_GN
//
//  Created by Nic on 2025/2/18.
//

import UIKit

class KLMNavigationController: UINavigationController, UINavigationControllerDelegate {
    
    override init(rootViewController: UIViewController) {
        super.init(rootViewController: rootViewController)
//        setupBarAppearance()
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
//        setupBarAppearance()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        delegate = self
        self.interactivePopGestureRecognizer?.delegate = self
//        setupBarAppearance()
    }
    
    private func setupBarAppearance() {
        let theme = KLMThemeManager.shared.currentTheme
        customNavBarAppearance(barTintColor: theme.navBarBgColor, titleColor: theme.navBarTextColor) { bar, appearence in
//            if #available(iOS 13.0, *) {
//                appearence?.shadowColor = .clear
//                appearence?.configureWithOpaqueBackground()
//            } else {
//                //去掉导航栏横线
////                bar?.setBackgroundImage(UIImage(), for: .default)
////                bar?.shadowImage = UIImage()
//                bar?.isTranslucent = false
//            }
        }
    }
    
    override func pushViewController(_ viewController: UIViewController, animated: Bool) {
                
        //允许
        self.interactivePopGestureRecognizer?.isEnabled = true
        
        if viewControllers.count > 0 {
            viewController.hidesBottomBarWhenPushed = true
            
            viewController.navigationItem.leftBarButtonItems = UIBarButtonItem.itemWithBackIcon(target: self, action: #selector(pushBack))
        }
        ///防止重复push相同的控制器
        if let vc: UIViewController = viewControllers.last, type(of: vc) == type(of: viewController) {
            return
        }
        super.pushViewController(viewController, animated: animated)
    }
    
    override func popToRootViewController(animated: Bool) -> [UIViewController]? {
        
        // 解决iOS 14 popToRootViewController tabbar不自动显示问题
        if animated {
            let popController = viewControllers.last
            popController?.hidesBottomBarWhenPushed = false
        }
        return super.popToRootViewController(animated: animated)
    }
            
    @objc func pushBack() {
        
        popViewController(animated: true)
    }
}


extension KLMNavigationController: UIGestureRecognizerDelegate {
    func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
        ///在rootviewcontroller侧滑会导致push卡住问题，所以禁用掉rootviewcontroller侧滑手势
        if gestureRecognizer == self.interactivePopGestureRecognizer {
            if visibleViewController == viewControllers.first {
                return false
            }
        }
        return true
    }
}
